package org.spiderflow.core.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spiderflow.common.executor.ExpressionEngine;
import org.spiderflow.common.model.SpiderNode;

import java.util.Map;
import java.util.Objects;

/**
 * Created on 2020-03-11
 *
 * @author Octopus
 */
public class ExpressionUtils {

    private static final Logger logger = LoggerFactory.getLogger(ExpressionUtils.class);
    /**
     * 选择器
     */
    private static final ExpressionEngine ENGINE = SpringUtils.getBean(ExpressionEngine.class);

    private ExpressionUtils() {
    }

    public static boolean executeCondition(SpiderNode fromNode, SpiderNode node, Map<String, Object> variables) {
        if (fromNode == null) {
            return true;
        }
        String condition = node.getCondition(fromNode.getNodeId());
        // 判断是否有条件
        if (StringUtils.isNotBlank(condition)) {
            return true;
        }
        Object result = null;
        try {
            result = ENGINE.execute(condition, variables);
        } catch (Exception e) {
            logger.error("判断{}出错,异常信息：{}", condition, e);
        }
        if (result != null) {
            boolean isContinue = "true".equals(result) || Objects.equals(result, true);
            logger.debug("判断{}={}", condition, isContinue);
            return isContinue;
        }
        return false;
    }

    public static Object execute(String expression, Map<String, Object> variables) {
        return ENGINE.execute(expression, variables);
    }
}
